<template>
  <AuFormModal
    ref="formModalRef"
    v-model="showModal"
    :title="title"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 460
    }"
    :formProps="{
      labelWidth: '60px',
      class: '!w-[426px]'
    }"
    @handleConfirm="handleConfirm"
  />
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { cloneDeep } from "lodash-unified";
import { ElMessage } from "element-plus";
import { taskTypeAdd, TaskTypeListProp, taskTypeUpd } from "@/api/expiry/task";

interface Props {
  modelValue: boolean;
  formData: TaskTypeListProp;
  lastSubId: number;
}

const props = defineProps<Props>();

const emits = defineEmits(["update:modelValue", "confirm"]);
const title = ref("");
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "名称",
    placeholder: "请输入名称",
    style: {
      width: "350px"
    },
    required: true
  },
  {
    type: "input",
    key: "note",
    label: "备注",
    placeholder: "请输入备注",
    style: {
      width: "350px"
    },
    inType: "textarea"
  }
]);
const selfFormData = ref({});
const formModalRef = ref();

const handleConfirm = async (data: any) => {
  let service = taskTypeAdd;
  if (data?.id) {
    service = taskTypeUpd;
  } else {
    data.subId = 100 + Number(props.lastSubId);
  }
  const res = await service(data);
  if (res.code == 200) {
    ElMessage({
      message: data?.id ? "编辑定时任务类型成功" : "新增定时任务类型成功",
      type: "success"
    });
    emits("update:modelValue", false);
    emits("confirm");
  }
};

watch(
  () => [props.modelValue, props.formData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as TaskTypeListProp;
      title.value = rowData?.id ? "编辑定时任务类型" : "新增定时任务类型";
      if (rowData?.id) {
        nextTick(() => {
          formModalRef.value.setFormData(row);
          formModalRef.value.setFormProps("copyVersion", { hidden: true });
        });
      } else {
        nextTick(() => {
          formModalRef.value.setFormData({});
        });
      }
    }
  }
);
</script>
